'use strict';

clientApp.controller('ListCtrl', function($scope, $location, model) {

  $scope.id = $location.search()['id'];

  if (!$scope.id) {

    $location.path('/');
    $scope.$apply();

  }

  $scope.list = model.List.get($scope.id);
  $scope.list.onchange = function() {

    $scope.$apply();

    // console.log('list', $scope.list);
  };

  $scope.listItems = model.ListItem.query().filter('ListId =', $scope.id).order('-Timestamp');
  $scope.listItems.onchange = function() {

    $scope.$apply();
   
    // console.log($scope.listItems);
  };

  $scope.newListItem = '';

  $scope.addItem = function() {

    var listItem = new model.ListItem();
    _.extend(listItem, {
      ListId: $scope.id,
      Creator: model.user.Name,
      Timestamp: Date.now(),
      Text: $scope.newListItem
    });
    listItem.$save();
    $scope.newListItem = '';

  };
});
